package org.example.interceptor;

import feign.Request;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.enums.BizCodeEnum;
import org.example.model.LoginUser;
import org.example.util.CommonUtil;
import org.example.util.JWTUtil;
import org.example.util.JsonData;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: HandlerInterceptor请求地址拦截器，比方法拦截器更早执行
 * @author: 谢超
 * @date: 2023/08/13 11:44
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private static final String TOKEN = "token";

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    /**
     * @param request  请求体
     * @param response 响应体
     * @param handler
     * @return
     * @throws Exception
     * @description: 目标方法执行完成之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果请求为options方法，则返回204请求
        if (Request.HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader(TOKEN);

        // 如果请求头token为空。尝试从参数里面获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(TOKEN);
        }

        // 获取到了后，则对token进行解密
        if (StringUtils.isNotBlank(token)) {
            Claims claims = JWTUtil.checkJWT(token);
            if (claims == null) {
                // 未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }

            long accountNo = Long.parseLong(claims.get("account_no").toString());
            String username = (String) claims.get("username");
            String headImg = (String) claims.get("head_img");
            String mail = (String) claims.get("mail");
            String phone = (String) claims.get("phone");
            String auth = (String) claims.get("auth");
            LoginUser loginUser = LoginUser
                    .builder()
                    .accountNo(accountNo)
                    .auth(auth)
                    .phone(phone)
                    .headImg(headImg)
                    .mail(mail)
                    .username(username)
                    .build();

            // 将loginUser传到controller层
            // 方式一: request.setAttribute("loginUser", loginUser);

            //方式二: 通过threadLocal
            threadLocal.set(loginUser);
            return true;
        }

        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     * @description: 目标方法执行完成之后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     * @description: 页面渲染以后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除threadLocal，防止内存泄漏
        threadLocal.remove();
    }
}
